<template>
  <div>
    <div class="citysaerch-wrapper">
      <input
        v-model="keyword"
        type="text"
        class="citysaerch-input"
        placeholder="输入城市名称或拼音"
        onkeyup="this.value=this.value.replace(/\s+/g,'')"
      >
    </div>
    <div ref="SerchCitys" class="serchcitys" v-show="keyword">
      <ul>
        <li
          class="searchitem"
          v-for="item in list"
          :key="item.id"
          @click="handelChangeCity(item.name)"
        >{{ item.name }}</li>
        <li class="searchitem" v-show="isshowData">没有找到相关城市~_~</li>
      </ul>
    </div>

  </div>
</template>

<script>
import BScroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    citys: Object
  },
  data () {
    return {
      keyword: '',
      timer: null,
      list: []
    }
  },
  methods: {
    handelChangeCity (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  computed: {
    isshowData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const res = []
        for (let i in this.citys) {
          this.citys[i].forEach(value => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              res.push(value)
            }
          })
        }
        this.list = res
      }, 100)
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.SerchCitys)
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .citysaerch-wrapper
    height: .64rem
    line-height: .64rem
    padding: .1rem
    background-color: $bgColor
    .citysaerch-input
      width: 100%
      height: .62rem
      text-align: center
      border-radius: .06rem
      touch-action: none
  .serchcitys
    position: absolute
    top: 1.7rem
    left: 0
    bottom: 0
    right: 0
    background: #f5f5f5
    overflow: hidden
    z-index: 1
    .searchitem
      padding: .2rem
      background: #fff
      border-bottom: .02rem solid #f5f5f5
</style>
